package yns.springframework.mvc.controller;

import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import yns.springframework.mvc.bean.User;

@RestController
@RequestMapping(value = "/guide2")
public class GuideController2 {

	/**
	 * Rest接口ajax获得的数据直接为json的对象。（无需再parse）
	 * 
	 * 
	 * @return
	 */
	@RequestMapping(value = "/restGuideMethod", produces = { MediaType.APPLICATION_JSON_VALUE })
	public String restGuideMethod() {
		System.out.println("restGuideMethod");

		JSONObject jsonObject = new JSONObject();
		jsonObject.put("info", "中文");
		jsonObject.put("key2", new JSONArray());
		jsonObject.put("html", "<p>Hello World!</p>");

		return jsonObject.toString();

	}

	/**
	 * 接受json格式的数据
	 * 
	 * 
	 * @param name
	 * @return
	 */
	@RequestMapping(value = "/restGuideMethod2", produces = { MediaType.APPLICATION_JSON_VALUE })
	public String restGuideMethod2(@RequestParam(value = "name", required = false) String name) {
		System.out.println("restGuideMethod2");
		System.out.println(name);

		JSONObject jsonObject = new JSONObject();
		jsonObject.put("name", name);

		return jsonObject.toString();

	}

	/**
	 * 接受POST数据，json格式
	 * 
	 * 
	 * @param user
	 * @return
	 */
	@RequestMapping(value = "/restGuideMethod3", produces = { MediaType.APPLICATION_JSON_VALUE }, method = RequestMethod.POST)
	public String restGuideMethod3(@ModelAttribute("user") User user) {
		System.out.println("restGuideMethod3");
		System.out.println(user.toString());

		JSONObject jsonObject = new JSONObject();
		jsonObject.put("user", user.toString());

		return jsonObject.toString();

	}
	
	/**
	 * Post 参数在Body里
	 * 
	 * 
	 * @param user
	 * @return
	 */
	@RequestMapping(value = "/restGuideMethod4", produces = { MediaType.APPLICATION_JSON_VALUE }, method = RequestMethod.POST)
	public String restGuideMethod4(@RequestBody String json) {
		System.out.println("restGuideMethod4");
		System.out.println(json);

		return JSONObject.toJSONString(json);

	}
}
